// 导入rouetr
import router from './router'
// 导入vuex
import store from './store'

// 导入nprogress
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 导入路由
import { asyncRouter } from '@/router'

// 进行导航守卫操作

let whiteList = ['/login', '/404']
// console.log(whiteList)
router.beforeEach(async (to, from, next) => {
    nprogress.start()
    if (store.getters.token) {
        if (to.path === '/login') {
            next('/')
        } else {
            // 如果没有用户id我们就执行获取用户信息
            if (!store.getters.userId) {
                // 获取用户信息
                let userInfo = await store.dispatch('user/getUserInfo')
                // 把筛选出来的路由对象,加到路由规则里
                let routes = await store.dispatch('permission/getAsyncRoutes', userInfo.roles.menus)
                router.addRoutes(routes)
                next(to.path)
            }
            // 既登录了而且去的也不是登录页，就正常放行
            // 就证明这里就是去后台的任何一个页面，不管去哪个页面都需要有用户信息
            next()
        }
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }
})
router.afterEach((to, from) => {
    nprogress.done()
})